<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;
class PayController extends Controller
{
    //会员付款
    public function pay($id)
    {

    	//查询订单数据
    	$data = DB::table('order') -> where('uid',$id) -> orderBy('id','desc') -> first();

    	return view('home.vip_service.pay',['data' => $data]);
    }

    //确认付款
    public function surePay(Request $request)
    {
    	$data = $request -> except('_token');

    	if($data['goods'] == '白金会员')
    	{
    		$type = 0;
    	}else
    	{
    		$type = 1;
    	}

    	//开启事务
    	DB::beginTransaction();

    	//查询老板账户金额
    	$bData = DB::table('vip') -> where('type',$type) -> first();
    	$bossAccount = $bData -> boss_account;

    	//查询用户金额
    	$id = Session::get('master') -> id;
    	$uData = DB::table('userdetail') -> where('uid',$id) -> first();

    	$userAccount = $uData -> account;

    	//付款金额
    	$account = $data['account'];

    	//付款后金额
    	$bossAccount += $account;
    	$userAccount -= $account;

        //判断用户金额是否充足
    	if($userAccount < $account)
    	{
    		return back() -> with(['info' => '余额不足']);
    	}

    	$res1 = DB::table('userdetail') -> where('uid',$id) -> update(['account' => $userAccount]);

        //判断是否购买成功
    	if(!$res1)
    	{
    		DB::rollBack();
    	}

    	$res2 = DB::table('vip') -> where('type',$type) -> update(['boss_account' => $bossAccount]);

    	if(!$res2)
    	{
    		DB::rollBack();
    	}

    	$res3 = DB::commit();

        if(!$res3)
        {
            DB::rollBack();
        }

    	//修改订单状态
    	//获取最后一次提交的订单ID
    	$newid = DB::table('order') -> where('num',$data['num']) -> first() -> id;
    	$res = DB::table('order') -> where('id',$newid) -> update(['access' => 1]);

        date_default_timezone_set('PRC');
        $time = time();

    	if($data['goods'] == '白金会员')
    	{
    		$auth = DB::table('users') -> where('id',$id) -> update(['auth' => 1,'buy_time' => $time]);
    	}else
    	{
    		$auth = DB::table('users') -> where('id',$id) -> update(['auth' => 2,'buy_time' => $time]);
    	}
    	
    	if($res)
    	{
            $users = DB::table('users') -> where('id',$id) -> first();
            Session::set('master',$users);
    		return view('home.vip.index');
    	}

    }
}
